package com.egd.imapp.contoller.activity.contact;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.egd.imapp.R;
import com.egd.imapp.contoller.adapter.InviteAdapter;
import com.egd.imapp.model.Model;
import com.egd.imapp.model.bean.InvitationInfo;
import com.egd.imapp.utils.Constant;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;

public class InviteActivity extends Activity {
    private EaseTitleBar tb_invite_list;
    private ListView lv_invite_list;
    private InviteAdapter inviteAdapter;

    private InviteAdapter.OnInviteListener mOnInviteListener = new InviteAdapter.OnInviteListener() {
        @Override
        public void onAccept(InvitationInfo invitationInfo) {

            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    // 通知环信服务器，接受好友邀请
                    try {
                        EMClient.getInstance().contactManager().acceptInvitation(invitationInfo.getUser().getHxid());

                        // 数据库更新
                        Model.getInstance().getDbManager().getInviteTableDao().
                                updateInvitationStatus(InvitationInfo.InvitationStatus.INVITE_ACCEPT, invitationInfo.getUser().getHxid());

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Toast.makeText(InviteActivity.this, "接受邀请", Toast.LENGTH_SHORT).show();

                                // 刷新页面
                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        Log.e(TAG, "run: 接受邀请失败"+e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "接受邀请失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }

        @Override
        public void onRefuse(InvitationInfo invitationInfo) {

            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        EMClient.getInstance().contactManager().declineInvitation(invitationInfo.getUser().getHxid());

//                        Model.getInstance().getDbManager().getInviteTableDao().removeInvitation(invitationInfo.getUser().getHxid());

                        // 数据库更新
                        Model.getInstance().getDbManager().getInviteTableDao().
                                updateInvitationStatus(InvitationInfo.InvitationStatus.INVITE_REJECT, invitationInfo.getUser().getHxid());

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝邀请成功", Toast.LENGTH_SHORT).show();

                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝邀请失败", Toast.LENGTH_SHORT).show();

                                refreshInfo();
                            }
                        });
                    }

                }
            });

        }


        // 接受群邀请按钮
        @Override
        public void onInviteAccept(InvitationInfo invitationInfo) {
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.e(TAG, "run: 告诉环信服务器接受了邀请 groupId = "+ invitationInfo.getGroup().getGroupId() + " 群名称 = "+ invitationInfo.getGroup().getGroupName() );

                        // 告诉环信服务器接受了邀请
                        EMClient.getInstance().groupManager().acceptInvitation(invitationInfo.getGroup().getGroupId(), invitationInfo.getGroup().getInvatePerson());

                        // 本地数据更新
                        invitationInfo.setStatus(InvitationInfo.InvitationStatus.GROUP_ACCEPT_INVITE);
                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo);
//                        Model.getInstance().getDbManager().getInviteTableDao().updateInvitationStatus(invitationInfo.getStatus(), invitationInfo.getGroup().getGroupId());


                        // 内存数据的变化
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "接受邀请成功", Toast.LENGTH_SHORT).show();

                                // 刷新页面
                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "接受邀请失败", Toast.LENGTH_SHORT).show();
                                Log.e(TAG, "run: 接受邀请失败 原因："+ e.getMessage() );
                            }
                        });
                    }
                }
            });
        }

        // 拒绝群邀请按钮
        @Override
        public void onInviteReject(InvitationInfo invitationInfo) {
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.e(TAG, "run: 告诉环信服务器拒绝了邀请 groupId = "+ invitationInfo.getGroup().getGroupId() + " 群名称 = "+ invitationInfo.getGroup().getGroupName() );

                        // 告诉环信服务器拒绝了邀请
                        EMClient.getInstance().groupManager().declineInvitation(invitationInfo.getGroup().getGroupId(), invitationInfo.getGroup().getInvatePerson(),"拒绝邀请");

                        // 更新本地数据库
                        invitationInfo.setStatus(InvitationInfo.InvitationStatus.GROUP_REJECT_INVITE);
                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo);

                        // 更新内存的数据
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝邀请成功", Toast.LENGTH_SHORT).show();

                                // 刷新页面
                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝邀请失败", Toast.LENGTH_SHORT).show();
                                Log.e(TAG, "run: 拒绝邀请失败 原因："+ e.getMessage() );
                            }
                        });
                    }
                }
            });
        }

        // 接受群申请按钮
        @Override
        public void onApplicationAccept(InvitationInfo invitationInfo) {
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 告诉环信服务器接受了申请
                        EMClient.getInstance().groupManager().acceptApplication(invitationInfo.getGroup().getGroupId(), invitationInfo.getGroup().getInvatePerson());

                        // 更新数据库
                        invitationInfo.setStatus(InvitationInfo.InvitationStatus.GROUP_ACCEPT_APPLICATION);
                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo);

                        // 更新内存
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "接受申请", Toast.LENGTH_SHORT).show();

                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // 拒绝群申请按钮
        @Override
        public void onApplicationReject(InvitationInfo invitationInfo) {
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 告诉环信服务器拒绝了申请
                        EMClient.getInstance().groupManager().declineApplication(invitationInfo.getGroup().getGroupId(), invitationInfo.getGroup().getInvatePerson(),"拒绝申请");

                        // 更新本地数据库
                        invitationInfo.setStatus(InvitationInfo.InvitationStatus.GROUP_REJECT_APPLICATION);
                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invitationInfo);

                        // 更新内存
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝申请", Toast.LENGTH_SHORT).show();

                                refreshInfo();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(InviteActivity.this, "拒绝申请失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }
    };
    private LocalBroadcastManager mLBM;
    private final BroadcastReceiver contactChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 刷新页面
            refreshInfo();
        }
    };
    private final String TAG = "TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite);
        
        initView();
        
        initData();

        initListener();
    }



    private void initData() {
        // 初始化ListView
        inviteAdapter = new InviteAdapter(this, mOnInviteListener);

        lv_invite_list.setAdapter(inviteAdapter);

        // 刷新数据方法
        refreshInfo();

        // 注册邀请信息变化的广播
        mLBM = LocalBroadcastManager.getInstance(this);
        mLBM.registerReceiver(contactChangedReceiver, new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
        mLBM.registerReceiver(contactChangedReceiver, new IntentFilter(Constant.GROUP_INVITE_CHANGED));

    }

    private void initListener() {
        tb_invite_list.setOnBackPressListener(new EaseTitleBar.OnBackPressListener() {
            @Override
            public void onBackPress(View view) {
                onBackPressed();
            }
        });
    }


    private void refreshInfo() {
        // 获取数据库表中的所有的邀请信息
        List<InvitationInfo> invitations = Model.getInstance().getDbManager().getInviteTableDao().getInvitations();

        inviteAdapter.refreshInfo(invitations);
    }

    private void initView() {

        tb_invite_list = findViewById(R.id.tb_invite_list);

        lv_invite_list = findViewById(R.id.lv_invite_list);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLBM.unregisterReceiver(contactChangedReceiver);
    }
}